# -*- coding: utf-8 -*-
import hashlib
import requests
import base64
import urllib
from datetime import datetime


def sign(secret, parameters):
    # ===========================================================================
    # '''签名方法
    # @param secret: 签名需要的密钥
    # @param parameters: 支持字典和string两种
    # '''
    # ===========================================================================
    # 如果parameters 是字典类的话
    if hasattr(parameters, "items"):
        keys = parameters.keys()
        keys = sorted(parameters)

        parameters = "%s%s%s" % (secret,
                                 str().join('%s%s' % (key, parameters[key]) for key in keys),
                                 secret)
    sign = hashlib.md5(parameters.encode('utf-8')).hexdigest().upper()
    return sign


def get_tao_key(text, gourl, logo):
    url = 'http://gw.api.taobao.com/router/rest'

    data = {
        'app_key': '24652066',
        'format': 'json',
        'method': 'taobao.tbk.tpwd.create',
        'sign_method': 'md5',
        'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        'v': '2.0',
        'text': text,
        'url': gourl,
        'logo': logo
    }

    sign_value = sign('fea4abb685d2e39140dc50764f943d05', data)
    data['sign'] = sign_value
    return requests.get(url, params=data).json()['tbk_tpwd_create_response']['data']['model']


def get_short_url(url):
    host = "http://dwz.wailian.work"
    url = base64.b64encode(url.encode('ascii'))
    params = [("url", url), ("site", "sina")]
    params = urllib.parse.unquote(urllib.parse.urlencode(params))
    url = urllib.parse.urljoin(host, "api.php?{0}".format(params))
    headers = {
        "Host": "dwz.wailian.work",
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
        "Cookie": "__cfduid=dd6009be7f2fc4046101581bea59a014b1507736943; PHPSESSID=n9m3h9tfkiious9rqpgt05pgd4; a2943_pages=1; a2943_times=1",
        "Accept": "application/json,text/javascript,*/*;q=0.01",
        "Connection": "keep-alive"
    }
    data = requests.get(url, headers=headers).json()
    print(data)
    status = data['result']
    if status.lower() == 'ok':
        return data['data']['short_url']
    else:
        return 'Error:'.format(data['data'])
